<script setup lang="ts">
import type { Vehicle, VehicleFormData } from '#/api/vehicle';

import { computed, nextTick, ref, watch } from 'vue';

import { ElForm } from 'element-plus';

import {
  checkLicensePlateExistsApi,
  createVehicleApi,
  updateVehicleApi,
  VehicleStatus,
} from '#/api/vehicle';

interface Props {
  modelValue: boolean;
  title: string;
  data?: null | Vehicle;
  isEdit?: boolean;
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void;
  (e: 'success'): void;
}

const props = withDefaults(defineProps<Props>(), {
  data: null,
  isEdit: false,
});

const emit = defineEmits<Emits>();

// 表单引用
const formRef = ref<InstanceType<typeof ElForm>>();

// 提交状态
const submitLoading = ref(false);

// 状态选项
const statusOptions = [
  { label: '可用', value: VehicleStatus.AVAILABLE },
  { label: '出车中', value: VehicleStatus.IN_USE },
  { label: '维保中', value: VehicleStatus.MAINTENANCE },
  { label: '停用', value: VehicleStatus.DISABLED },
];

// 表单数据
const formModel = ref<VehicleFormData>({
  licensePlate: '',
  brand: '',
  model: '',
  color: '',
  purchaseDate: '',
  insuranceDue: '',
  inspectionDue: '',
  status: VehicleStatus.AVAILABLE,
  fuelConsumption: undefined,
});

// 弹框显示状态
const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val),
});

// 表单校验规则
const formRules = computed(() => ({
  licensePlate: [
    { required: true, message: '请输入车牌号' },
    { min: 7, max: 8, message: '车牌号长度应为7-8位' },
    {
      validator: async (_rule: any, value: string, callback: any) => {
        if (!value) return;

        // 车牌号格式校验
        const licensePlateRegex =
          /^[京津沪渝冀豫云辽黑湘鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼][A-Z][A-Z0-9]{4,5}[A-Z0-9挂学警港澳]?$/;
        if (!licensePlateRegex.test(value)) {
          callback(new Error('车牌号格式不正确'));
          return;
        }

        // 编辑模式下不检查唯一性
        if (props.isEdit) {
          callback();
          return;
        }

        // 检查唯一性
        try {
          const exists = await checkLicensePlateExistsApi(value);
          if (exists) {
            callback(new Error('该车牌号已存在，请更换'));
          } else {
            callback();
          }
        } catch (error) {
          console.error('检查车牌号失败:', error);
          callback();
        }
      },
      trigger: 'blur',
    },
  ],
  status: [{ required: true, message: '请选择车辆状态' }],
  fuelConsumption: [
    {
      validator: (_rule: any, value: any, callback: any) => {
        if (value === undefined || value === null || value === '') {
          callback();
          return;
        }
        if (value < 0 || value > 100) {
          callback(new Error('标准油耗应在0-100升/百公里之间'));
        } else {
          callback();
        }
      },
      trigger: 'blur',
    },
  ],
}));

// 监听数据变化，初始化表单
watch(
  () => [props.modelValue, props.data],
  async ([visible, data]) => {
    if (visible) {
      await nextTick();
      if (data && typeof data === 'object') {
        // 编辑模式，填充数据
        formModel.value = {
          licensePlate: data.licensePlate,
          brand: data.brand || '',
          model: data.model || '',
          color: data.color || '',
          purchaseDate: data.purchaseDate || '',
          insuranceDue: data.insuranceDue || '',
          inspectionDue: data.inspectionDue || '',
          status: data.status,
          fuelConsumption: data.fuelConsumption || undefined,
        };
      } else {
        // 新增模式，重置表单
        formModel.value = {
          licensePlate: '',
          brand: '',
          model: '',
          color: '',
          purchaseDate: '',
          insuranceDue: '',
          inspectionDue: '',
          status: VehicleStatus.AVAILABLE,
          fuelConsumption: undefined,
        };
      }
      // 重置表单校验
      formRef.value?.clearValidate();
    }
  },
  { immediate: true },
);

// 取消
function handleCancel() {
  visible.value = false;
}

// 关闭弹框回调
function handleClosed() {
  // 重置表单
  formRef.value?.clearValidate();
  formModel.value = {
    licensePlate: '',
    brand: '',
    model: '',
    color: '',
    purchaseDate: '',
    insuranceDue: '',
    inspectionDue: '',
    status: VehicleStatus.AVAILABLE,
    fuelConsumption: undefined,
  };
}

// 提交表单
async function handleSubmit() {
  try {
    // 表单校验
    await formRef.value?.validate();

    submitLoading.value = true;

    // 提交数据
    if (props.isEdit) {
      await updateVehicleApi(props.data!.vehicleId, formModel.value);
      ElMessage.success('更新成功');
    } else {
      await createVehicleApi(formModel.value);
      ElMessage.success('创建成功');
    }

    // 关闭弹框并通知父组件
    visible.value = false;
    emit('success');
  } catch (error: any) {
    if (error?.message) {
      ElMessage.error(error.message);
    } else {
      console.error('提交失败:', error);
      ElMessage.error('提交失败，请重试');
    }
  } finally {
    submitLoading.value = false;
  }
}
</script>

<template>
  <ElDialog
    v-model="visible"
    :title="title"
    width="680px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @closed="handleClosed"
    class="vehicle-dialog"
  >
    <ElForm
      ref="formRef"
      :model="formModel"
      :rules="formRules"
      label-width="120px"
      class="mt-6 space-y-6"
    >
      <ElFormItem label="车牌号" prop="licensePlate">
        <ElInput
          v-model="formModel.licensePlate"
          placeholder="请输入车牌号"
          :disabled="isEdit"
          maxlength="8"
          show-word-limit
        />
      </ElFormItem>

      <ElFormItem label="车辆品牌" prop="brand">
        <ElInput
          v-model="formModel.brand"
          placeholder="请输入车辆品牌"
          maxlength="50"
          class="w-full"
        />
      </ElFormItem>

      <ElFormItem label="车辆型号" prop="model">
        <ElInput
          v-model="formModel.model"
          placeholder="请输入车辆型号"
          maxlength="100"
          class="w-full"
        />
      </ElFormItem>

      <ElFormItem label="颜色" prop="color">
        <ElInput
          v-model="formModel.color"
          placeholder="请输入颜色，如：白色、黑色"
          maxlength="20"
          class="w-full"
        />
      </ElFormItem>

      <ElFormItem label="购买日期" prop="purchaseDate">
        <ElDatePicker
          v-model="formModel.purchaseDate"
          type="date"
          placeholder="选择购买日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          class="w-full"
        />
      </ElFormItem>

      <ElFormItem label="保险到期日" prop="insuranceDue">
        <ElDatePicker
          v-model="formModel.insuranceDue"
          type="date"
          placeholder="选择保险到期日"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          class="w-full"
        />
      </ElFormItem>

      <ElFormItem label="年检到期日" prop="inspectionDue">
        <ElDatePicker
          v-model="formModel.inspectionDue"
          type="date"
          placeholder="选择年检到期日"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          class="w-full"
        />
      </ElFormItem>

      <ElFormItem label="车辆状态" prop="status">
        <ElSelect
          v-model="formModel.status"
          placeholder="请选择车辆状态"
          class="w-full"
        >
          <ElOption
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </ElSelect>
      </ElFormItem>

      <ElFormItem label="标准油耗" prop="fuelConsumption">
        <ElInputNumber
          v-model="formModel.fuelConsumption"
          :min="0"
          :max="100"
          :precision="1"
          :step="0.1"
          placeholder="请输入标准油耗"
          class="w-full"
        >
          <template #append>升/百公里</template>
        </ElInputNumber>
      </ElFormItem>
    </ElForm>

    <template #footer>
      <div class="flex justify-end space-x-3 pt-4">
        <ElButton @click="handleCancel" class="rounded-lg px-6 py-2">
          取消
        </ElButton>
        <ElButton
          type="primary"
          :loading="submitLoading"
          @click="handleSubmit"
          class="rounded-lg px-6 py-2 shadow-md transition-shadow duration-200 hover:shadow-lg"
        >
          确定
        </ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<style scoped>
/* 对话框样式优化 */
:deep(.vehicle-dialog) {
  overflow: hidden;
  border-radius: 16px;
}

:deep(.vehicle-dialog .el-dialog__header) {
  padding: 24px 32px;
  margin: 0;
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
  border-bottom: 1px solid #e2e8f0;
}

:deep(.vehicle-dialog .el-dialog__title) {
  font-size: 20px;
  font-weight: 600;
  color: #1e293b;
}

:deep(.vehicle-dialog .el-dialog__body) {
  padding: 32px;
  background: #fff;
}

:deep(.vehicle-dialog .el-dialog__footer) {
  padding: 20px 32px;
  background: #f8fafc;
  border-top: 1px solid #e2e8f0;
}

/* 表单样式优化 */
:deep(.el-form-item__label) {
  font-size: 14px;
  font-weight: 500;
  color: #374151;
}

:deep(.el-input__wrapper) {
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 4px 0 rgb(0 0 0 / 5%);
  transition: all 0.2s ease;
}

:deep(.el-input__wrapper:focus-within) {
  box-shadow:
    0 0 0 3px rgb(59 130 246 / 10%),
    0 2px 4px 0 rgb(0 0 0 / 5%);
}

:deep(.el-select__wrapper) {
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 4px 0 rgb(0 0 0 / 5%);
  transition: all 0.2s ease;
}

:deep(.el-date-editor) {
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 4px 0 rgb(0 0 0 / 5%);
  transition: all 0.2s ease;
}

:deep(.el-input-number) {
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 4px 0 rgb(0 0 0 / 5%);
  transition: all 0.2s ease;
}

/* 按钮样式优化 */
:deep(.el-button) {
  font-weight: 500;
  border-radius: 10px;
  transition: all 0.2s ease;
}

/* 表单间距优化 */
:deep(.el-form-item) {
  margin-bottom: 24px;
}

:deep(.el-form-item:last-child) {
  margin-bottom: 0;
}

/* 输入框统一宽度 */
:deep(.el-input),
:deep(.el-select),
:deep(.el-date-editor),
:deep(.el-input-number) {
  width: 100% !important;
}
</style>
